package com.example.administrator.caigou51.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.ab.util.AbSharedUtil;
import com.alibaba.fastjson.JSON;
import com.example.administrator.caigou51.R;
import com.example.administrator.caigou51.bean.TitleBean;
import com.example.administrator.caigou51.global.App;
import com.example.administrator.caigou51.global.Constant;
import com.example.administrator.caigou51.recyclerCard.basic.MaterialListView;
import com.example.administrator.caigou51.recyclerCard.card.SearchCard;
import com.example.administrator.caigou51.request.BaseResponse;
import com.example.administrator.caigou51.request.ICallBackForRequestServer;
import com.example.administrator.caigou51.request.RequestServerManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/18/018.
 */
public class SearchActivity extends GBaseActivity implements View.OnClickListener{

    MaterialListView material_listview;
    ImageView imageViewRight,imageViewError;
    EditText editTextSearch;
    public static final String SearchTag="SearchTag";
    public static final String SearchBeanList="SearchBeanList";

    List<TitleBean> titleBeanList;
    SearchCard searchCard;
    View imageViewBack;
    private boolean isRepeat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentViewFor720_1280(R.layout.activity_search);
        //   EventBus.getDefault().register(this);
        findViewByIds();
        initDatas();
        TaskGetSearchData(false);
    }


    protected void findViewByIds() {
        material_listview= (MaterialListView) findViewById(R.id.material_listview);
        imageViewRight= (ImageView) findViewById(R.id.imageViewRight);imageViewRight.setOnClickListener(this);
        editTextSearch= (EditText) findViewById(R.id.editTextSearch);
        imageViewError= (ImageView) findViewById(R.id.imageViewError);imageViewError.setOnClickListener(this);
        imageViewBack=findViewById(R.id.imageViewBack);imageViewBack.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
     //   if (titleBeanList!=null)
     //   fillArrayInListView(titleBeanList);
        if (searchCard!=null)
        {
            String json=AbSharedUtil.getString(App.getInstance().getApplicationContext(),SearchActivity.SearchBeanList);
            if (!TextUtils.isEmpty(json)) {
                List<TitleBean> listlast = JSON.parseArray(json,TitleBean.class);
                searchCard.getTitleBeanLastList().clear();
                searchCard.getTitleBeanLastList().addAll(listlast);
                material_listview.getAdapter().notifyDataSetChanged();
            }
        }

    }

    protected void initDatas()
    {
        getTopBar().setVisibility(View.GONE);
        editTextSearch.setText("");

            imageViewError.setVisibility(View.GONE);

        editTextSearch.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int editStart ;
            private int editEnd ;
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                temp = s;
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
//          mTextView.setText(s);//将输入的内容实时显示
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                editStart = editTextSearch.getSelectionStart();
                editEnd = editTextSearch.getSelectionEnd();

                if (temp.length() > 0) {
                    imageViewError.setVisibility(View.VISIBLE);
                }else
                {
                    imageViewError.setVisibility(View.GONE);
                }
            }
        });
    }

    protected void fillArrayInListView(List<TitleBean> list) {
        material_listview.clear();
         searchCard =new SearchCard(this);
        searchCard.setMaterialListView(material_listview);
        searchCard.setTitleBeanList(list);
        //获取最近的标签
        String json=AbSharedUtil.getString(App.getInstance().getApplicationContext(),SearchActivity.SearchBeanList);
        if (!TextUtils.isEmpty(json)) {
            List<TitleBean> listlast = JSON.parseArray(json,TitleBean.class);
            searchCard.setTitleBeanLastList(listlast);
        }else
        {
            searchCard.setTitleBeanLastList(new ArrayList<TitleBean>());
        }

        material_listview.add(searchCard);
    }
    /*public void onEventMainThread(UpdateSearchGoodsViewPager updateSearchGoodsViewPager) {
        searchGoodsMainCard.getViewPager().getLayoutParams().height=2000;
        searchGoodsMainCard.getViewPager().invalidate();
    }*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId())
        {
            case R.id.imageViewRight:
                Intent intent=new Intent(this, SearchGoodsActivity.class);
                intent.putExtra(SearchActivity.SearchTag,editTextSearch.getText().toString());
                startActivity(intent);
                //保存搜索标签
                isRepeat=false;
                String json=AbSharedUtil.getString(App.getInstance().getApplicationContext(),SearchActivity.SearchBeanList);
                if (!TextUtils.isEmpty(editTextSearch.getText().toString())) {
                    if (!TextUtils.isEmpty(json)) {
                        List<TitleBean> listlast = JSON.parseArray(json, TitleBean.class);

                        for (int i=0;i<listlast.size();i++)
                        {
                            if (listlast.get(i).getTitle().equals(editTextSearch.getText().toString()))
                            {
                                isRepeat=true;
                                break;
                            }
                        }
                        if (!isRepeat) {
                            TitleBean titleBean = new TitleBean();
                            titleBean.setTitle(editTextSearch.getText().toString());
                            listlast.add(titleBean);
                            AbSharedUtil.putString(App.getInstance().getApplicationContext(), SearchActivity.SearchBeanList, JSON.toJSONString(listlast));
                        }
                    } else {
                        List<TitleBean> list = new ArrayList<TitleBean>();
                        TitleBean titleBean = new TitleBean();
                        titleBean.setTitle(editTextSearch.getText().toString());
                        list.add(titleBean);
                        AbSharedUtil.putString(App.getInstance().getApplicationContext(), SearchActivity.SearchBeanList, JSON.toJSONString(list));
                    }
                }
                break;
            case R.id.imageViewError:
                editTextSearch.setText("");
                break;
            case R.id.imageViewBack:
                finish();
                break;
        }
    }

    private void TaskGetSearchData(final boolean isRefresh) {
        RequestServerManager.getInstanceDIY().handleMethodDIY((GBaseActivity) getActivity(), material_listview, isRefresh, null,
                Constant.getRootUrl() + Constant.Action.Action_HotSearch, Constant.Action.Action_HotSearch, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_HotSearch), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {

                        // JSONObject jsonObject = (JSONObject) result.getData();
                        titleBeanList = JSON.parseArray(result.getData().toString(),TitleBean.class);
                        fillArrayInListView(titleBeanList);
                        //  Log.e("userBean",JSON.toJSONString(goodsBean));
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }


}
